import { useCallback, useMemo, useRef, useState, forwardRef,useImperativeHandle, Ref } from 'react';
import {Button, Drawer} from 'antd'
import Core from './core'
import { Schema } from "./types";
import css from './index.less'
import { setSchemaMap } from './constants';
import { getSchemaByData } from './utils';

function JsonEditor ({value, onChange, editor, title, typeMap, inline}:{
    title?: string, 
    value?:Schema, 
    onChange?:(value?:Schema) => void,
    editor?: boolean,
    typeMap?: object
    inline?: boolean
}, fRef:Ref<{getValue: () => Promise<Schema>}>){
    const [visible, $visible] = useState(false)
    const ref = useRef<{getValue: () => Promise<Schema>}>(null);
    const handleClick = useCallback(() => {
        ref.current?.getValue().then(res => {
            $visible(false)
            onChange?.(res)
        });
    }, [onChange])
    
    const key = useMemo(() => Math.random().toString().slice(2), [value])
    useMemo(() => {
        if (typeMap) {
            setSchemaMap(typeMap)
        }
    }, [typeMap]);

    useImperativeHandle(fRef, () => ({
        getValue: () => ref.current?.getValue?.()!
    }), [])
    return value ? <div className={css.box}>
        {
            title && <p>{title}</p>
        }
        {
           (editor && inline) ? <Core value={value} key={key} editor ref={ref} /> : <Core value={value} key={key} />
        }
        {
            editor && !inline &&  <>
                <span className={css.editorBtn} onClick={() => $visible(true)}>编辑</span>
                <Drawer
                    visible={visible}
                    title="编辑类型"
                    onClose={() => $visible(false)}
                    destroyOnClose
                    footer={
                        <div className={css.footer}>
                            <Button onClick={() => $visible(false)}>取消</Button>
                            <Button  type="primary" onClick={handleClick}>确定</Button>
                        </div>
                    }
                >
                    <Core value={value} editor ref={ref} />
                </Drawer>
            </>
        }
    </div>: null
}
export default forwardRef(JsonEditor)
export type {Schema}
export {getSchemaByData}
/*
Schema 格式
{
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "data": {
            "type": "array",
            "items": {
                "type": "number"
            }
        }
    }
}
*/